package com.mimo.logic.user.grpc;

import org.springframework.beans.factory.annotation.Autowired;

import com.google.protobuf.StringValue;
import com.mimo.common.configuration.broadcast.MultiCastRegistry;
import com.mimo.common.logic.code.StatusCode;
import com.mimo.common.rpc.proto.BaseResponseProto.BaseResponse;
import com.mimo.common.rpc.proto.LogicUserProxyGrpc;
import com.mimo.common.rpc.proto.UserProto.UserLoginReq;
import com.mimo.logic.config.heartbeat.annotation.ExcludeHeartbeat;
import com.mimo.logic.event.UserStatusActionEvent;
import com.mimo.logic.event.UserStatusActionType;
import com.mimo.logic.user.service.IUserService;

import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;

@ExcludeHeartbeat
@GrpcService
public class LogicUserGrpc extends LogicUserProxyGrpc.LogicUserProxyImplBase {

  @Autowired
  private IUserService userService;

  @Override
  public void login(UserLoginReq request, StreamObserver<BaseResponse> responseObserver) {
    StatusCode code = userService.login(com.mimo.common.comet.dto.user.UserLoginReq.convert(request));
    if (code.isSuccess()) {
      MultiCastRegistry.INSTANCE
          .publish(new UserStatusActionEvent(this, userService.load(request.getUid()), UserStatusActionType.Login));
    }

    responseObserver.onNext(code.toResp());
    responseObserver.onCompleted();
  }

  @Override
  public void logout(StringValue request, StreamObserver<BaseResponse> responseObserver) {
    StatusCode code = userService.logout(request.getValue());
    MultiCastRegistry.INSTANCE
        .publish(new UserStatusActionEvent(this, userService.load(request.getValue()), UserStatusActionType.Logout));
    responseObserver.onNext(code.toResp());
    responseObserver.onCompleted();
  }

}
